<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="120px">
      <el-form-item label="任务ID" prop="id">
        <el-input
          v-model="queryParams.id"
          placeholder="请输入任务ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户ID" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入用户ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="任务名称" prop="tasksName">
        <el-input
          v-model="queryParams.tasksName"
          placeholder="请输入任务名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="任务状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择任务状态" clearable>
          <el-option
            v-for="dict in dict.type.wp_tasks_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="任务创建时间" prop="createTime">
        <el-date-picker clearable
                        v-model="queryParams.createTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择任务创建时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="任务更新时间" prop="updateTime">
        <el-date-picker clearable
                        v-model="queryParams.updateTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择任务更新时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="分组名称" prop="openaiMsgGroupsId">
        <el-input
          v-model="queryParams.openaiMsgGroupsId"
          placeholder="请输入分组名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['tasks:tasks:add']"
        >创建文章标题</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="openArticlesTasks"
          v-hasPermi="['tasks:tasks:add']"
        >创建文章</el-button>
      </el-col>
<!--      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['tasks:tasks:edit']"
        >修改</el-button>
      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['tasks:tasks:remove']"
        >删除</el-button>
      </el-col>
<!--      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['tasks:tasks:export']"
        >导出</el-button>
      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="tasksList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="任务的唯一标识符" align="center" prop="id" />
      <el-table-column label="提交任务的用户ID" align="center" prop="userId" />
      <el-table-column label="任务名称" align="center" prop="tasksName" />
      <el-table-column label="总重复次数" align="center" prop="totalRepetitions" />
      <el-table-column label="每次请求的重复次数" align="center" prop="repetitionsPerRequest" />
      <el-table-column label="已完成的重复次数" align="center" prop="repetitionsCompleted" />
      <el-table-column label="任务类型" align="center" prop="tasksType" />
      <el-table-column label="活动值(开发者看的)" align="center" prop="tasksOption" />
      <el-table-column label="任务状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.wp_tasks_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="运行的分组请求名称" align="center" prop="openaiMsgGroupsId" />
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['tasks:tasks:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['tasks:tasks:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改存储任务信息的对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="任务名称" prop="tasksName">
          <el-input v-model="form.tasksName" :disabled="true" placeholder="请输入任务名称" />
          <div class="sub-title">注：自动生成名称无需填写</div>
        </el-form-item>
        <el-form-item label="运行的分组名称" prop="tasksOption">
          <el-select v-model="form.tasksOption" placeholder="请选择运行的分组名称" filterable clearable
                     :style="{width: '100%'}">
            <el-option v-for="(item, index) in parentList" :key="index" :label="item.parentCategoryName"
                       :value="item.parentCategoryId" :disabled="item.disabled"></el-option>
          </el-select>
          <div class="sub-title">选择文章标题分组，默认读取这一个组里面的所有关键词生成标题</div>
        </el-form-item>
        <el-form-item label="重复次数" prop="totalRepetitions">
          <el-input-number v-model="form.totalRepetitions" :min="1" :max="10"  placeholder="输入总重复次数" label="描述文字"></el-input-number>
          <div class="sub-title">注：重复十次，生成十个内容，目前最多一次性十个</div>
        </el-form-item>
        <el-form-item label="请求次数" prop="repetitionsPerRequest" >
          <el-input-number v-model="form.repetitionsPerRequest" :min="1" :max="50"  placeholder="请输入请求次数" label="描述文字"></el-input-number>
          <div class="sub-title">注：请求十次，重复十次，那就是一百次</div>
        </el-form-item>
      </el-form>
      <div class="sub-title">注：如果你的分组里面有10个关键词，重复十次，重复请求十次，那么将会创建一千个标题，10*10*10</div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <ArticlesTasks :visible.sync="articlesTasksDialogVisible"   :parentList="parentList"/>

  </div>
</template>

<script>
import { listTasks, getTasks, delTasks, addTasks, updateTasks } from "@/api/tasks/tasks";
import { listCategoryParentId } from '@/api/dict/category'
import ArticlesTasks from './articlesTasks.vue';

export default {
  name: "Tasks",
  dicts: ['wp_tasks_type', 'wp_tasks_status'],
  components: {
    ArticlesTasks
  },
  data() {
    return {
      parentList:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 存储任务信息的表格数据
      tasksList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        id: null,
        userId: null,
        tasksName: null,
        totalRepetitions: null,
        repetitionsPerRequest: null,
        repetitionsCompleted: null,
        status: null,
        createTime: null,
        updateTime: null,
        openaiMsgGroupsId: null,
        tasksOption:null,
        tasksType:null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        status: [
          { required: true, message: "任务状态不能为空", trigger: "change" }
        ],
        tasksType: [
          { required: true, message: "任务类型(1、写标题，2、写文章，3、用户自定义，0、其他)不能为空", trigger: "change" }
        ],
        totalRepetitions: [
          { required: true, message: "总重复次数不能为空", trigger: "blur" },
          { type: "number", min: 0, max: 10, message: "总重复次数必须在0到10之间", trigger: "blur" }
        ],
        repetitionsPerRequest: [
          { required: true, message: "请求次数不能为空", trigger: "blur" },
          { type: "number", min: 0, max: 50, message: "请求次数必须在0到50之间", trigger: "blur" }
        ]
      },
      articlesTasksDialogVisible:false
    };
  },
  created() {
    this.getList();
  },
  methods: {
    openArticlesTasks(){
      this.articlesTasksDialogVisible = true;
    },
    getCurrentDateTime() {
      const now = new Date();
      const month = now.getMonth() + 1; // 月份从0开始，所以需要加1
      const date = now.getDate();
      const hours = now.getHours();
      const minutes = now.getMinutes();
      const formattedDateTime = `${month}-${date}-${hours}-${minutes}`;
      return formattedDateTime;
    },
    /** 查询存储任务信息的列表 */
    getList() {
      this.loading = true;
      listTasks(this.queryParams).then(response => {
        this.tasksList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      listCategoryParentId().then(response => {
        console.log(" this.parentList")
        console.log(response.rows)
        this.parentList = response.rows
        console.log(this.parentList)
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        userId: null,
        tasksName: null,
        totalRepetitions: null,
        repetitionsPerRequest: null,
        repetitionsCompleted: null,
        status: null,
        createTime: null,
        updateTime: null,
        tasksType: null,
        openaiMsgGroupsId: null,
        tasksOption:null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.form.tasksType = 1;
      this.title = "添加标题创建任务(注意这是写标题！)";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getTasks(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改存储任务信息的";
      });
    },
    /** 提交按钮 */
    submitForm() {
      // 在提交表单之前，根据选中的下拉框值生成任务名称
      const selectedItem = this.parentList.find(item => item.parentCategoryId === this.form.tasksOption);
      if (selectedItem) {
        this.form.tasksName = this.getCurrentDateTime()+"-"+`${selectedItem.parentCategoryName}-${this.form.totalRepetitions}-${this.form.repetitionsPerRequest}`;
      }else {
        this.$modal.msgError("请选择分组名称");
        return
      }
      this.form.openaiMsgGroupsId = 1;
      console.log(this.form )
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateTasks(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTasks(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除存储任务信息的编号为"' + ids + '"的数据项？').then(function() {
        return delTasks(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('tasks/tasks/export', {
        ...this.queryParams
      }, `tasks_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
